package cn.lazydong.dbproperties.config;

import cn.lazydong.dbproperties.DbPropertiesUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author HeLingdong
 */
@ConditionalOnBean(DbPropertiesCustom.class)
public class DbPropertyBeanCollect implements InstantiationAwareBeanPostProcessor {

    public static final Map<String, List<SpringValue>> ALL_VALUE_BEAN = new ConcurrentHashMap<>();

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        Field[] declaredFields = beanClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            if (!declaredField.isAnnotationPresent(Value.class)) {
                continue;
            }
            String value = declaredField.getAnnotation(Value.class).value();
            if(!isValueFormat(value)){
                continue;
            }
            String[] split = value.substring(2, value.length() - 1).split(":");
            if (!DbPropertiesUtil.isExistSysPropertySource(split[0])) {
                if (split.length == 1) {
                    DbPropertiesUtil.addPropertySource(split[0], "");
                }
            }
        }
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> aClass = bean.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            if (!declaredField.isAnnotationPresent(Value.class)) {
                continue;
            }
            String value = declaredField.getAnnotation(Value.class).value();
            if(!isValueFormat(value)){
                continue;
            }
            SpringValue springValue = new SpringValue();
            springValue.setBean(bean);
            springValue.setDeclaredField(declaredField);
            springValue.setAccessible(declaredField.isAccessible());
            String[] split = value.substring(2, value.length() - 1).split(":");
            springValue.setKey(split[0]);
            if (split.length > 1) {
                springValue.setDefValue(split[1]);
            }
            if (ALL_VALUE_BEAN.containsKey(split[0])) {
                DbPropertyBeanCollect.ALL_VALUE_BEAN.get(split[0]).add(springValue);
            } else {
                List<SpringValue> list = new ArrayList<>();
                list.add(springValue);
                ALL_VALUE_BEAN.put(split[0], list);
            }
        }
        return bean;
    }

    @SuppressWarnings("all")
    private boolean isValueFormat(String value){
        if (!(value.startsWith("${") || value.startsWith("#{"))) {
            return false;
        }
        return value.endsWith("}");
    }
}
